package com.tzy.parser.core.strategy;


import com.tzy.parser.core.AttributeParser;
import com.tzy.parser.core.Constant;

import java.util.LinkedList;

//解析  and  or   not
public class LogicalTemplateStrategy implements TemplateStrategy{

    private AttributeParser parser;


    public LogicalTemplateStrategy(AttributeParser parser) {
        this.parser = parser;
    }

    @Override
    public String strategyName() {
        return "logical";
    }

    @Override
    public boolean canParse(String template) {
        return Constant.isLogicalOperations(template);
    }

    @Override
    public Object parse(String template, Object meta) {


        if (meta == null || template == null) {
            return null;
        }

        template=template.trim();

        //not  表达式
        if(template.startsWith(Constant.NOT)){

            String substring = template.substring(Constant.NOT.length());

            Object o = parser.baseParse(meta, substring);
            return ! Boolean.parseBoolean(o.toString());

        }



        String[] tempArray = template.split(" ");

        LinkedList<String> strings = new LinkedList<>();

        String optString = null;

        for (String temp : tempArray) {

            if(temp.equals(Constant.AND)){

                optString=Constant.AND;

                continue;

            }


            if(temp.equals(Constant.OR)){

                optString=Constant.OR;

                continue;

            }

            strings.add(temp);

            if(optString!=null){
                if(optString.equals(Constant.AND)){

                    String pop01 = strings.pop();
                    String pop02 = strings.pop();

                    temp = Boolean.valueOf(Boolean.parseBoolean(parser.baseParse(meta, pop01).toString())
                            && Boolean.parseBoolean(parser.baseParse(meta, pop02).toString())).toString();

                }

                if(optString.equals(Constant.OR)){

                    String pop01 = strings.pop();
                    String pop02 = strings.pop();

                    temp = Boolean.valueOf(Boolean.parseBoolean(parser.baseParse(meta, pop01).toString())
                            || Boolean.parseBoolean(parser.baseParse(meta, pop02).toString())).toString();

                }

                strings.add(temp);

            }


            optString=null;

        }




        return Boolean.valueOf(strings.getFirst());
    }
}
